/**
 * Created by Administrator on 2017/2/24.
 */

import {allUrl} from '../scripts/url'
import {Toast,checkLogin,getFormatDateByLong} from '../scripts/tip'


export const  initPresetOrderDetail =(productDetailId,count,voucherMoney,voucherSecret,productId) => {

     count=parseFloat(count);

    $.getJSON(''+allUrl()+'mall/queryPresetOrderDetail', {
        productDetailId:productDetailId,
        count: count
    }, (data) => {

        checkLogin(data, false, '');

        if(data.head.returnCode===0){
            if(data.head.subCode===0){
                var result=data.body;
                showDetails(result,productDetailId,count,voucherMoney,voucherSecret,productId)
            }else{
                Toast(data.head.subMsg,2000,'');
            }
        }else {
            Toast(data.head.returnMsg,2000,'');
        }

    })
};

function showDetails(result,productDetailId,count,voucherMoney,voucherSecret,productId){


    var express,address,idNumber,rproductType,realName,telephone,productId,product,productUrl,productName,color,size,productPrice,province,city,dist,gender,height,wechatId;

    product=result.product;
    express=result.express;

    address=express.address||'';
    realName=express.realName||'';
    telephone=express.telephone||'';
    idNumber=express.idNumber||'';
    gender=express.gender||0;
    height=express.height||'';
    wechatId=express.wechatId||'';
    rproductType=result.product.productType;
    productId=product.productId;
    productUrl=product.category.productUrl;
    productName=product.productName;
    color=product.category.color;
    size=product.category.size;
    productPrice=product.category.productPrice;

    province=express.province||'';
    city=express.city||'';
    dist=express.dist||'';

    if(rproductType===1){

        if(idNumber!=''||realName!=''||telephone!=''){

            $('.noneAddr .titleWrap').addClass('hide');
            $('.noneAddr .addr-infor').removeClass('hide');

            $('.addr-inforWrap .realName').text('收货人：'+realName+'');
            $('.addr-inforWrap .telephone').text('收货人：'+telephone+'');
            $('.addr-inforWrap .addressIdNumber').text('身份证号：'+idNumber+' ');

        }else {
            $('.noneAddr .titleWrap').removeClass('hide');
            $('.noneAddr .addr-infor').addClass('hide');
            $('.titleWrap title').html('请填写收货信息')
        }
        $('.titleWrap').attr('href','#/mall/address?productType=1');
    }else {

        if(address!=''||realName!=''||telephone!=''){

            $('.noneAddr .titleWrap').addClass('hide');
            $('.noneAddr .addr-infor').removeClass('hide');

            $('.addr-inforWrap .realName').text('收货人：'+realName+'');
            $('.addr-inforWrap .telephone').text('收货人：'+telephone+'');

            $('.addr-inforWrap .addressIdNumber').text('收货地址：'+province+' '+city+' '+dist+' '+address+' ');

        }else {
            $('.noneAddr .titleWrap').removeClass('hide');
            $('.noneAddr .addr-infor').addClass('hide');
            $('.titleWrap title').html('请填写收货信息')
        }

        $('.titleWrap').attr('href','#/mall/address?productType=0');
    }


    $('.addr-infor').click(function(){
        if(rproductType){
            location.href='#/mall/address?productType=1'
        }else {
            location.href='#/mall/address?productType=0'
        }
    });


    $('.PresetOrderDetail .order-imge .product-img').css({background:'url("'+productUrl+'")',backgroundSize:'100% 100%'});
    $('.PresetOrderDetail .MyOrderList .order-name h1').html(productName);
    $('.PresetOrderDetail .MyOrderList .order-name h2 span:first-child').html(color);
    $('.PresetOrderDetail .MyOrderList .order-name h2 span:last-child').html(size);

    $('.PresetOrderDetail .MyOrderList .order-price h1').html('￥'+productPrice+'');
    $('.PresetOrderDetail .MyOrderList .order-price h2').html('X'+count+'');

    $('.OrderDetailsTicket .ticket ').attr('href','#/mall/voucher?productId='+productId+'&productDetailId='+productDetailId+'&count='+count+'');


    var totalReward=result.reward.totalReward;
    var voucherLimit=product.category.voucherLimit;

      function compareRewardLimit(){

          var countRT=parseFloat(voucherMoney)+totalReward;

          if(voucherMoney>=voucherLimit){
              $('.PresetOrderDetail .MyOrderList .reward .subtitle').html('共'+totalReward+'元红包，可用'+0+'元');
              $('.PresetOrderDetail .MyOrderList .reward .money .realMoney').html(0);
              $('.PresetOrderDetail .ticketUse ').html("-￥<span class='realUseTicket hasTicket'>"+voucherLimit+"</span>");
          }else {
              if(countRT<=voucherLimit){
                  $('.PresetOrderDetail .MyOrderList .reward .subtitle').html('共'+totalReward+'元红包，可用'+totalReward+'元');
                  $('.PresetOrderDetail .MyOrderList .reward .money .realMoney').html(totalReward);

              }else {
                  $('.PresetOrderDetail .MyOrderList .reward .subtitle').html('共'+totalReward+'元红包，可用'+(voucherLimit-voucherMoney)+'元');
                  $('.PresetOrderDetail .MyOrderList .reward .money .realMoney').html(voucherLimit-voucherMoney);
              }
          }

          if(voucherMoney===0){

              $('.PresetOrderDetail  .ticketUse ').html("未使用抵用券");
              $('.PresetOrderDetail .ticketUse ').removeClass('hasTicket')
          }else {
              $('.PresetOrderDetail  .ticketUse ').addClass('hasTicket');
              $('.PresetOrderDetail .ticketUse ').html("-￥<span class='realUseTicket hasTicket'>"+voucherMoney+"</span>");
          }
      }

    compareRewardLimit();

    $('.PresetOrderDetail .OrderDetailsTicket .freight .realFreight').html(express.freight);

    var realReward,realPrice;

    $('.reward ').on('click','.radioBtn',function(){

        if($(this).hasClass('noSelect')){

            $(this).removeClass('noSelect');

            compareRewardLimit();

            realReward=parseFloat($('.PresetOrderDetail .reward .money .realMoney').html());

        }else {
            $(this).addClass('noSelect');

            $('.PresetOrderDetail .MyOrderList .reward .money .realMoney').html(0);

            realReward=0;
        }

        $('.PresetOrderDetail .payDetails .reward span:last-child').html('-￥'+realReward+'');

        realPrice=(product.category.productPrice*count-realReward-realTicket+express.freight).toFixed(2);

        if(realPrice<0){realPrice=0}

        $('.PresetOrderDetail .payDetails .realPrice span:last-child').html('￥'+realPrice+'');
    });


   realReward=parseFloat($('.PresetOrderDetail .reward .money .realMoney').html());

    var Ticket=$('.PresetOrderDetail .ticketUse .realUseTicket').html()||0;

    var realTicket=parseFloat(Ticket);

     realPrice=(product.category.productPrice*count-realReward-realTicket+express.freight).toFixed(2);

    if(realPrice<0){realPrice=0}

    $('.PresetOrderDetail .payDetails .price span:last-child').html('￥'+product.category.productPrice+'');
    $('.PresetOrderDetail .payDetails .reward span:last-child').html('-￥'+realReward+'');
    $('.PresetOrderDetail .payDetails .ticket span:last-child').html('-￥'+realTicket+'');
    $('.PresetOrderDetail .payDetails .freight span:last-child').html('+￥'+express.freight+'');
    $('.PresetOrderDetail .payDetails .realPrice span:last-child').html('￥'+realPrice+'');

    function  addOrder(){

        $.post(''+allUrl()+'mall/addCustomerOrder', {
            productId:productId,
            productType:rproductType,
            productName:productName,
            productDetailId:productDetailId,
            color:color,
            size:size,
            productPrice:productPrice,
            count:count,
            actualPrice:realPrice,
            freight:express.freight,
            voucherSecret:voucherSecret,
            voucherMoney:voucherMoney,
            rewardMoney:realReward,
            realName:realName,
            telephone:telephone,
            province:province,
            city:city,
            dist:dist,
            address:address,
            gender:gender,
            idNumber:idNumber,
            height:height,
            wechatId:wechatId
        }, (datasource) => {

            datasource=$.parseJSON(datasource);

            if(datasource.head.returnCode===0){

                if(datasource.head.subCode===0){
                    var sign,orderNumber,payAmount,productName;

                    sign=datasource.body.sign;
                    orderNumber=datasource.body.orderNumber;
                    payAmount=datasource.body.payAmount;
                    productName=datasource.body.productName;

                    asyncPay(sign,productName,payAmount,orderNumber)

                }else {
                    Toast(datasource.head.subMsg,2000,'');
                }
            }else {
                Toast(datasource.head.returnMsg,2000,'');
            }
        })
      }

    $('.addOrder').click(function(){

        addOrder()
    })
}


function bcPay(sign,productName,payAmount,orderNumber) {

    BC.err = function(data) {
        alert(data["ERROR"]);
    };

    BC.click({
        "title":productName, //商品名
        "amount":payAmount,  //总价（分）
        "out_trade_no":orderNumber, //自定义订单号
        "instant_channel":"ali",//设置后直接调用支付
        "use_app":false,
        "optional": {"test": "willreturn"},
        "sign":sign, //商品信息hash值，含义和生成方式见下文
        "return_url" : "https://mall.leqibike.com/paySuccess.html" //支付成功后跳转的商户页面,可选，默认为http://payservice.beecloud.cn/spay/result.php
    });
}

function asyncPay(sign,productName,payAmount,orderNumber) {
    if (typeof BC == "undefined"){
        if( document.addEventListener ){
            document.addEventListener('beecloud:onready', bcPay, false);
        }else if (document.attachEvent){
            document.attachEvent('beecloud:onready', bcPay);
        }
    }else{
        bcPay(sign,productName,payAmount,orderNumber);
    }
}






